﻿using System;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using VCC.CMS.Properties;
using VCC.CMS.ViewModels;
using VCC.Lib.Common;
using VCC.Lib.Helpers;
using VCC.Model;
namespace VCC.CMS.Controllers
{
    public class CategoryController : BaseController
    {

        
        #region GET: /Category/Index
        [RoleHelper(Roles = RoleSystem.AdCategory)]
        public ActionResult Index()
        {
            ChoVietDataContext eDataContext = new ChoVietDataContext();
            try
            {
                    string order = UserState.getUserStateFromRequest("category.order", "order", "ID").ToString();
                    string orderDir = UserState.getUserStateFromRequest("category.orderDir", "orderDir", "desc").ToString();
                    int parentID = Convert.ToInt32(UserState.getUserStateFromRequest("category.parentID", "parentID", 0));
                    ViewData["orderDir"] = orderDir;
                    ViewData["order"] = order;
                    return View(new CategoryIndexViewModel
                    {
                        CategoryBuiltTree = Model.CategoryManager.BuiltCombobox(0),
                        ParentCatIDs = eDataContext.Categories.Where(e => e.ParentID == null || e.ParentID == 0).Select(e => e.ID.ToString()).ToList()   
                    });
                
                    
            }
            catch (Exception exp)
            {
                eDataContext.Dispose();
                ViewData["MessageInfo"] = "0#" + exp.Message;
                return View();
            }
        }
        #endregion

        #region GET: /Category
        [RoleHelper(Roles = RoleSystem.AdCategory)]
        public ActionResult Details(int id)
        {
            ChoVietDataContext eDataContext = new ChoVietDataContext();
            var param = eDataContext.Categories.FirstOrDefault(e => e.ID == id);
            return View(param);
        }
        #endregion

        #region GET: /Category/Create
        public ActionResult Create()
        {
            ChoVietDataContext eDataContext = new ChoVietDataContext();
            try
            {
                var listParent = eDataContext.Categories.Where(c => c.ParentID == null).ToList();

                return View(new CategoryEditViewModel() { ParrentCatrgories = listParent});
            }
            finally { eDataContext.Dispose();}
        }
        #endregion

        #region POST: /Category/Create
        [RoleHelper(Roles = RoleSystem.AdCategory)]
        [HttpPost] 
        public ActionResult Create(CategoryEditViewModel c)
        {
            ChoVietDataContext eDataContext = new ChoVietDataContext();
            try
            {
                if (eDataContext.Connection.State == System.Data.ConnectionState.Closed) eDataContext.Connection.Open();
                eDataContext.Transaction = eDataContext.Connection.BeginTransaction();
                UpdateModel(c);
                c.Category.CreatedBy = UserManager.GetUserId();
                c.Category.CreatedDate = DateTime.Now;

                eDataContext.Categories.InsertOnSubmit(c.Category);
                eDataContext.SubmitChanges();
                //Image display
                HttpPostedFileBase fileImage = Request.Files["catimage"];
                if (fileImage != null && fileImage.ContentLength > 0)
                {
                    c.Category.ImagePath = Uploads.UploadFile(fileImage, Settings.Default.CMSRootUrl,Settings.Default.SiteRootPath,c.Category.ID.ToString());
                }
                eDataContext.SubmitChanges();
                eDataContext.Transaction.Commit();
                ViewData["MessageInfo"] = "1#" + "Thêm chuyên mục thành công";
                return RedirectToAction("Index");
            }
            catch
            {
                eDataContext.Transaction.Rollback();
                eDataContext.Dispose();
                return View();
            }
        }
        #endregion

        #region GET: /Category/Edit/5
        public ActionResult Edit(int id)
        {
            ChoVietDataContext eDataContext = new ChoVietDataContext();
            try
            {
                var param = new CategoryEditViewModel();
                param.Category = eDataContext.Categories.Where(e => e.ID == id).SingleOrDefault();
                param.ParrentCatrgories = eDataContext.Categories.Where(e => e.ParentID == null || e.ParentID ==0).ToList();
                return View(param);
            }
            catch (Exception exp)
            {
                eDataContext.Dispose();
                ViewData["MessageInfo"] = exp.Message;
                return View();
            }
        }
        #endregion

        #region POST: /Category/Edit/5
        [HttpPost]
        public ActionResult Edit(int id, CategoryEditViewModel c)
        {
            ChoVietDataContext eDataContext = new ChoVietDataContext();
            try
            {
                if (eDataContext.Connection.State == System.Data.ConnectionState.Closed) eDataContext.Connection.Open();
                eDataContext.Transaction = eDataContext.Connection.BeginTransaction();
                c.Category = eDataContext.Categories.Where(cat => cat.ID == id).SingleOrDefault();
                UpdateModel(c);
                c.Category.ModifyBy = UserManager.GetUserId();
                c.Category.ModifyDate= DateTime.Now;
                eDataContext.SubmitChanges();
                //Image display
                HttpPostedFileBase fileImage = Request.Files["catimage"];
                if (fileImage != null && fileImage.ContentLength > 0)
                {
                    //Delete old icon
                    Uploads.DeleteFile(Settings.Default.CMSRootPath + c.Category.ImagePath);
                    //var nextid = (eDataContext.Ads.Max(e => e.ID) + 1).ToString();
                    c.Category.ImagePath = Uploads.UploadFile(fileImage, Settings.Default.CMSRootUrl,Settings.Default.SiteRootPath, c.Category.ID.ToString());
                }
                eDataContext.SubmitChanges();
                eDataContext.Transaction.Commit();
                ViewData["MessageInfo"] = "1#" + "Sửa chuyên mục thành công";
                return RedirectToAction("Index");
                }
            catch(Exception exp)
            {
                eDataContext.Transaction.Rollback();
                eDataContext.Dispose();
                ViewData["MessageInfo"] ="1#"+ exp.Message;
                return View();
            }
        }
        #endregion

        #region GET: /Department/Delete/5
        [RoleHelper(Roles = RoleSystem.AdCategory)]
        public ActionResult Delete(int id)
       {
           ChoVietDataContext eDataContext = new ChoVietDataContext();
           try
           {
               if (UserManager.CheckRole(RoleSystem.AdCategory))
               {
                   var item = eDataContext.Categories.Single(e => e.ID == id);
                   return View(item);
               }
               else
               {
                   Messages.AddErrorFlashMessage("Bạn không có quyền truy cập ứng dụng này");
                   ViewData["MessageInfo"] = "Bạn không có quyền truy cập ứng dụng này";
                   return View();
               }
           }
           catch (Exception exp)
           {
               ViewData["MessageInfo"] = exp.Message;
               return View();
           }
       }
        #endregion

        #region POST: /Department/Delete/5
        [HttpPost]
        public ActionResult Delete(int id, FormCollection collection)
       {
           ChoVietDataContext eDataContext = new ChoVietDataContext();
           try
           {
               if (UserManager.CheckRole(RoleSystem.AdCategory))
               {
                   var ads = eDataContext.Ads.Where(e => e.CatID == id).ToList();
                   if (ads.Count() > 0)
                   {
                       foreach (var item in ads)
                       {
                           if (item.Galleries.Count() > 0)
                           {
                               eDataContext.Galleries.DeleteAllOnSubmit(item.Galleries.ToList());
                               eDataContext.SubmitChanges();
                           }
                       }
                       eDataContext.Ads.DeleteAllOnSubmit(ads);
                       eDataContext.SubmitChanges();
                   }
                   var it = eDataContext.Categories.Single(e => e.ID == id);
                   if (it != null)
                   {
                       eDataContext.Categories.DeleteOnSubmit(it);
                       eDataContext.SubmitChanges();
                   }
                   return RedirectToAction("Index");
               }
               else
               {
                   ViewData["MessageInfo"] = "Bạn không có quyền truy cập ứng dụng này!";
                   return View();
               }
           }
           catch (Exception exp)
           {
               ViewData["MessageInfo"] = exp.Message;
               return View();
           }
       }
       #endregion
    }
}
